import Toast from '@vant/weapp/toast/toast';

Page({
  data: {
    basketItems: [],
    showDialog: false,
    emptyCartImage: '/assets/image/empty_cart.svg', // 使用 SVG 图片
    defaultFoodImage:
      'https://cdn.pixabay.com/photo/2017/05/07/08/56/food-2290814_1280.jpg',
    orderSubmitted: false,
    remark: '',
    selectedTime: '',
    timeArray: [
      ['今天', '明天', '后天'],
      ['早餐', '午餐', '晚餐'],
      [
        '06:00',
        '07:00',
        '08:00',
        '09:00',
        '10:00',
        '11:00',
        '12:00',
        '13:00',
        '14:00',
        '15:00',
        '16:00',
        '17:00',
        '18:00',
        '19:00',
        '20:00',
        '21:00'
      ]
    ],
    timeIndex: [0, 2, 10] // 默认选择今天晚餐18:00
  },

  onLoad(options) {
    // 页面加载时的逻辑
    this.initTimeSelector();
  },

  onShow() {
    // 从缓存中获取购物篮数据
    this.loadBasketData();

    // 获取订单提交状态
    const orderSubmitted = wx.getStorageSync('orderSubmitted') || false;
    this.setData({orderSubmitted});
  },

  // 初始化时间选择器
  initTimeSelector() {
    const now = new Date();
    const hour = now.getHours();
    let timeIndex = this.data.timeIndex;

    // 根据当前时间设置默认选项
    if (hour < 10) {
      timeIndex = [0, 0, hour - 6 >= 0 ? hour - 6 : 0]; // 早餐
    } else if (hour < 16) {
      timeIndex = [0, 1, hour - 6 >= 0 ? hour - 6 : 0]; // 午餐
    } else {
      timeIndex = [0, 2, hour - 6 >= 0 ? hour - 6 : 0]; // 晚餐
    }

    // 更新默认选择的时间
    this.setData({timeIndex});
    this.updateSelectedTime(timeIndex);
  },

  // 更新选择的时间
  updateSelectedTime(timeIndex) {
    const {timeArray} = this.data;
    const selectedTime = `${timeArray[0][timeIndex[0]]} ${
      timeArray[1][timeIndex[1]]
    } ${timeArray[2][timeIndex[2]]}`;
    this.setData({selectedTime});
  },

  // 时间选择器变化事件
  bindTimeChange(e) {
    const timeIndex = e.detail.value;
    this.setData({timeIndex});
    this.updateSelectedTime(timeIndex);
  },

  // 备注输入事件
  onRemarkInput(e) {
    this.setData({
      remark: e.detail.value
    });
  },

  // 加载购物篮数据
  loadBasketData() {
    const basket = wx.getStorageSync('basket') || {};
    const basketItems = Object.values(basket);

    this.setData({basketItems});
  },

  // 删除菜品
  deleteItem(e) {
    const id = e.currentTarget.dataset.id;
    let basket = wx.getStorageSync('basket') || {};

    if (basket[id]) {
      delete basket[id];
      wx.setStorageSync('basket', basket);
      this.loadBasketData();

      // 提示用户
      Toast.success('已删除');
    }
  },

  // 跳转到点菜页面
  goToOrder() {
    wx.switchTab({
      url: '/pages/order/index'
    });
  },

  // 跳转到历史菜单页面
  goToHistory() {
    wx.navigateTo({
      url: '/pages/history_menu/index'
    });
  },

  // 提交订单
  submitOrder() {
    if (this.data.basketItems.length === 0) {
      Toast.fail('菜单为空');
      return;
    }

    this.setData({
      showDialog: true
    });
  },

  // 确认提交订单
  handleConfirm() {
    const {basketItems, remark, selectedTime} = this.data;

    // 构建历史菜单数据
    const todayMenu = {
      id: Date.now(),
      date: selectedTime || '今日',
      dishes: basketItems,
      remark: remark,
      createdAt: new Date().toISOString()
    };

    // 获取历史菜单列表
    let historyMenus = wx.getStorageSync('historyMenus') || [];

    // 添加新的历史菜单
    historyMenus.unshift(todayMenu);

    // 最多保存10条历史记录
    if (historyMenus.length > 10) {
      historyMenus = historyMenus.slice(0, 10);
    }

    // 保存历史菜单和今日菜单
    wx.setStorageSync('historyMenus', historyMenus);
    wx.setStorageSync('todayMenu', todayMenu);

    // 清空购物篮
    wx.setStorageSync('basket', {});

    // 设置订单已提交状态
    wx.setStorageSync('orderSubmitted', true);

    // 关闭对话框
    this.setData({
      showDialog: false,
      basketItems: [],
      orderSubmitted: true
    });

    // 显示提交成功提示
    Toast.success({
      message: '菜单提交成功',
      forbidClick: true,
      duration: 1500
    });
  },

  // 查看今日菜单
  viewTodayMenu() {
    wx.navigateTo({
      url: '/pages/history_menu/index?viewToday=true'
    });
  },

  // 继续点菜
  continueOrder() {
    // 重置订单已提交状态
    wx.setStorageSync('orderSubmitted', false);

    this.setData({
      orderSubmitted: false
    });

    // 跳转到点菜页面
    wx.switchTab({
      url: '/pages/order/index'
    });
  },

  // 取消提交订单
  handleCancel() {
    this.setData({
      showDialog: false
    });
  }
});
